<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\facade\Db;
use think\Request;
use think\facade\View;

class Crud extends AdminBase
{
    private $tplPath        = '../app/common/.tpl/';
    private $modelPath      = '../app/common/model/';
    private $controllerPath = '../app/admin/controller/';
    private $validatePath   = '../app/validate/';
    private $viewPath       = '../view/admin/';

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $rs = Db::query('select * from information_schema.tables where TABLE_SCHEMA="' . config('database.connections.mysql.database') . '"');

        View::assign('tables', $rs);
        return View::fetch();
    }


    public function build(Request $request)
    {
        $except    = ['AdminBase', 'Common', 'Crud', 'Index', 'Role', 'Rule', 'Tool', 'admin_user', 'AdminUserRole', 'AdminUserRule'];
        $step      = $request->get('step', 1, 'intval');
        $force     = $request->get('force', false);
        $exists    = [];
        $tableName = $request->get('name');

        $name = $this->makeName($tableName);
        if (in_array($name, $except)) {
            return $this->error($name . ' 不允许操作!');
        }
        $list = [
            $this->tplPath . 'controller.tpl.php' => ['namespace' => 'app\\common\\model\\' . $name, 'savefile' => $this->controllerPath . $name . '.php'],
            $this->tplPath . 'model.tpl.php'      => ['namespace' => 'app\\admin\\controller\\' . $name, 'savefile' => $this->modelPath . $name . '.php'],
            $this->tplPath . 'validate.tpl.php'   => ['namespace' => 'app\\validate\\' . $name, 'savefile' => $this->validatePath . $name . '.php'],
            $this->tplPath . 'index_view.tpl.php' => ['savefile' => $this->viewPath . $tableName . '/index.html'],
            $this->tplPath . 'add_view.tpl.php'   => ['savefile' => $this->viewPath . $tableName . '/add.html'],
            $this->tplPath . 'edit_view.tpl.php'  => ['savefile' => $this->viewPath . $tableName . '/edit.html'],
        ];

        if ($step == 1) {

        } elseif ($step == 2) {
            $fieldList = \think\facade\Db::query('SHOW FULL COLUMNS FROM ' . $tableName);

            //检查是否存在
            foreach ($list as $k => $v) {
                //echo $v;
                if (file_exists($v['savefile'])) {

                    //已存在
                    $exists[] = $v['savefile'];
                }
            }
            if (!$exists || $request->get('force')) {
                foreach ($list as $k => $v) {
                    ob_start();
                    if (isset($v['namespace'])) {
                        $namespace = $v['namespace'];
                    } else {
                        unset($namespace);
                    }
                    require_once($k);
                    $content = ob_get_clean();
                    $tmp     = explode('/', $v['savefile']);
                    $path    = str_replace($tmp[count($tmp) - 1], '', $v['savefile']);
                    if (!is_dir($path)) {
                        mkdir($path);
                    }
                    file_put_contents($v['savefile'], $content);


                }
            }
        }
        View::assign('force', $force);
        View::assign('step', $step);
        View::assign('list', $list);
        View::assign('tableName', $tableName);
        View::assign('exists', $exists);
        return View::fetch();
    }

    /**
     * 生成名称
     * @param string $name
     * @return string
     */
    protected function makeName(string $name): string
    {
        $str = '';
        $arr = explode('_', $name);
        if ($arr) {
            foreach ($arr as $k => $v) {
                $str .= ucfirst($v);
            }
        } else {
            $str = $name;
        }
        return $str;
    }

    /**
     * 获取validate类型
     * @param string $type
     * @return string
     */
    protected function getRuleType(string $type): string
    {
        $ruleType = [
            'int'      => 'number',
            'integer'  => 'number',
            'bigint'   => 'number',
            'datetime' => 'datetime',
            'date'     => 'date'
        ];
        return isset($ruleType[$type]) ? $ruleType[$type] : '';
    }

}
